package server;

import java.io.*;
import java.util.Arrays;

import msgs.*;
/**
 * Gets/Sets profiles for the admin
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class AdminProfileWorker extends Thread implements TTConstants{
	private AdminRequestMsg armsg;
	
	public AdminProfileWorker(AdminMsg amsg) {
		this.armsg = (AdminRequestMsg) amsg;
	}
	
	public void run() {
		// can we yell at them to GTFO?
		if (!(Arrays.equals(armsg.getAdminKey(), TTServer.adminTable.get(armsg.getName()).getClientKey()))) {
			armsg.setResponse(Responses.DENY);
			AdminSender.outQ.add((AdminMsg) armsg);
			return;
		}
		
		// guess not.
		switch(armsg.getAction()) {
		case GETPROFILE: 
			File f = new File("data/profiles/"+armsg.getUser());
			if (f.exists()) {
				try {
					ObjectInputStream oir = new ObjectInputStream(new FileInputStream(f));
					armsg.setO((String)oir.readObject());
					oir.close();
				}
				catch (Exception e) {
					e.printStackTrace();
					armsg.setO(null);
				}
			}
			else armsg.setO(null);
			break;
		case SETPROFILE:
			File of = new File("data/profiles/"+armsg.getUser());
			try {
				ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(of));
				oos.writeObject((String)armsg.getO());
				oos.close();
			}
			catch(Exception e) { e.printStackTrace(); }
			break;
		}
		armsg.setResponse(Responses.OK);
		AdminSender.outQ.add((AdminMsg)armsg);
	}
	
}
